package com.guofeng.rich.gateway.router;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.guofeng.rich.gateway.constant.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;

import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: guofeng
 * @Date: 2021/08/20/10:56
 * @Description:
 */
@Configuration
@Slf4j
public class routerConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("auth-router-id", r -> r.path("/oauth/**")
                        .filters(f -> f.modifyResponseBody(String.class, String.class,
                                //s ==> 返回的 响应对象
                                (exchange, s) -> {
                                    String path = exchange.getRequest().getPath().value();
                                    //判断返回地址是否是 成功的回调地址
                                    if (path.equalsIgnoreCase("/oauth/token")) {
                                        //判断返回值
                                        if (!StringUtils.isEmpty(s)) {
                                            log.info(s);
                                            //解析返回地址
                                            JSONObject parseObj = JSONUtil.parseObj(s);
                                            //解析里面的数据
//                                            JSONObject parseData = JSONUtil.parseObj(parseObj.getStr("data"));
                                            if(parseObj != null){
                                                String accessToken = parseObj.getStr("access_token");
                                                if (!StringUtils.isEmpty(accessToken)) {
                                                    //获取token的过期时间
                                                    Long expiresIn = parseObj.getLong("expires_in");
                                                    redisTemplate.opsForValue().set(GatewayConstant.TOKEN_PREFIX + accessToken, "1", TimeUnit.SECONDS.toSeconds(expiresIn));
                                                }
                                            }

                                        }
                                    }
                                    return Mono.just(s);
                                })).uri("lb://auth-sever")).build();
    }
}
